import axios from 'axios'
export class AxiosRetry {
  constructor ({ url, onSuccess = () => {}, onError = () => {} }) {
    this.url = url
    this.onSuccess = onSuccess
    this.onError = onError
    this.fetchNewTokenPromise = null
    this.lastRequestTime = new Date()
    this.Requests = []
    this.reLoginWindowShow = false
  }

  requestWrapper (request, options) {
    return new Promise((resolve, reject) => {
      request(options)
        .then((val) => {
          this.fetchNewTokenPromise = null
          this.lastRequestTime = new Date()
          resolve(val)
        })
        .catch((err) => {
          if ((err.data && (err.data.code == 403 || err.data.code == 401)) || (err.response && (err.response.status === 403 || err.response.status === 401))) {
            this.Requests.push({
              cb: (token) => {
                options.headers.Authorization = token
                request(options).then(resolve).catch(reject)
              }
            })
            if (this.fetchNewTokenPromise) return
            this.fetchNewTokenPromise = this.fetchToken
            this.fetchNewTokenPromise()
              .then((token) => {
                this.Requests.forEach(({ cb }) => {
                  cb(token)
                })
              })
              .catch(error => {
                this.onError(error)
              })
              .finally(() => {
                this.Requests = []
                this.fetchNewTokenPromise = null
              })
          } else {
            reject(err)
          }
        })
    })
  }

  fetchToken () {
    var timeoutSet = JSON.parse(sessionStorage.getItem('timeOutParams'))
    return new Promise((resolve, reject) => {
      if (timeoutSet && timeoutSet.expires_in) {
        const noOperationTime = new Date() - this.lastRequestTime
        console.log(timeoutSet.expires_in * 1000, noOperationTime)
        if (timeoutSet.expires_in * 1000 < noOperationTime) {
          return reject(new Error('token已过期'))
        }
        var formData = new FormData()
        formData.append('client_id', 'nordrassil')
        formData.append('client_secret', 'nordrassil')
        formData.append('grant_type', 'client_credentials')
        formData.append('scope', 'manager')
        formData.append('payload', timeoutSet.nextPayloadKey)
        sessionStorage.removeItem('timeOutParams')
        // 验证PayLoad拿到Token
        axios
          .post(this.url, formData)
          .then(res => {
            if (res.data.token_type === 'bearer' && res.data.nextPayloadKey) {
              this.onSuccess(res.data)
              resolve('Bearer ' + res.data.access_token)
            } else {
              reject(new Error('token已过期'))
            }
          }).catch(reject)
      } else {
        return reject(new Error('token已过期'))
      }
    })
  }
}
